<?php

namespace app\admin\controller\video;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 视频合集管理
 *
 * @icon fa fa-circle-o
 */
class Collection extends Backend
{

    /**
     * Collection模型对象
     * @var \app\admin\model\video\Collection
     */
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\video\Collection;
        $this->view->assign("isRecommendList", $this->model->getIsRecommendList());
        $this->view->assign("isHotList", $this->model->getIsHotList());
        $this->view->assign("isFeaturedList", $this->model->getIsFeaturedList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','cover_image','video_count','play_count','user_count','is_recommend','is_hot','is_featured','weigh','status']);
                $row->title = htmlspecialchars_decode($row->title);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //主键搜索
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? $searchfield : explode(',', $searchfield);
                foreach ($word as $k => $v) {
                    $query->where(implode($logic, array_map(function ($m) {return "`{$m}` LIKE ?";}, $searchfield)), array_fill(0, count($searchfield), "%{$v}%"));
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 视频列表
     */
    public function videos()
    {
        $collection_id = $this->request->param('collection_id');
        if ($this->request->isAjax()) {
            $list = \app\common\model\Video::where('collection_id', $collection_id)
                ->order('weigh DESC,id DESC')
                ->select();
            
            return json(['total' => count($list), 'rows' => $list]);
        }
        
        $this->assignconfig('collection_id', $collection_id);
        return $this->view->fetch();
    }

    /**
     * 添加视频
     */
    public function videoadd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $result = \app\common\model\Video::create($params);
            if ($result) {
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑视频
     */
    public function videoedit($ids = null)
    {
        $row = \app\common\model\Video::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['updatetime'] = time();
            if ($row->save($params)) {
                $this->success();
            }
            $this->error();
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除视频
     */
    public function videodel($ids = "")
    {
        if ($ids) {
            $result = \app\common\model\Video::where('id', 'in', $ids)->delete();
            if ($result) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 开通用户列表
     */
    public function users()
    {
        $collection_id = $this->request->param('collection_id');
        if ($this->request->isAjax()) {
            $list = \app\common\model\UserVideo::with(['user'])
                ->where('collection_id', $collection_id)
                ->order('id DESC')
                ->select();
            
            return json(['total' => count($list), 'rows' => $list]);
        }
        
        $this->assignconfig('collection_id', $collection_id);
        return $this->view->fetch();
    }

    /**
     * 添加开通用户
     */
    public function useradd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['createtime'] = time();
            if($params['expiretime']) {
                $params['expiretime'] = strtotime($params['expiretime']);
            }
            $result = \app\common\model\UserVideo::create($params);
            if ($result) {
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 删除开通用户
     */
    public function userdel($ids = "")
    {
        if ($ids) {
            $result = \app\common\model\UserVideo::where('id', 'in', $ids)->delete();
            if ($result) {
                $this->success();
            }
        }
        $this->error();
    }

    /**
     * 批量开通用户视图
     */
    public function batch_user_video($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            $collection_ids = explode(',', $params['ids']);
            $i = 0;
            foreach ($collection_ids as $collection_id) {
                $status = \app\common\model\UserVideo::where(['collection_id'=>$collection_id,'user_id'=>$params['user_id']])->find();
                if(!$status) {
                    $insertData = [
                        'user_id' => $params['user_id'],
                        'collection_id' => $collection_id,
                        'createtime' => time()
                    ];
                    \app\common\model\UserVideo::create($insertData);
                    $i++;
                }
            }
            $this->success(__('Success %d', $i));
        }
        $this->view->assign('ids', $ids);
        return $this->view->fetch();
    }
}
